//
//  PreViewCell.m
//  Weibbo
//
//  Created by lilg on 13-6-23.
//  Copyright (c) 2013年 Omnivores. All rights reserved.
//

#import "PreViewCell.h"
#import "UIViewAdditions.h"
#import <CoreText/CoreText.h>
#import "NSAttributedString+Attributes.h"

#define Lines  3
#define ViewOffSetX      20.0f
#define ViewOffSetY      5.0f

#define ViewOffSetQuotationX      50.0f
#define LabWidthQuotation           250.0f
#define LabWidth          280.f
#define ExpendImageWidth   280.0f

@implementation PreViewCell
@synthesize originItem;
+ (float)heightForItem:(DraftItem *)item  IsExpand:(BOOL)expend
{
    if ([item isPlain]) {
        return CellHeight;
    }
    float height = 0;
    BOOL  isImage = [item isImage];
    if (isImage) {
        UIImage  *image = [item getImage];
        CGRect frame = [PreViewCell rectWithImageSize:image.size Expend:expend];
        height =  frame.size.height + ViewOffSetY;
    }else{
        CGSize size;
        if (expend) {
            size = [[item text] sizeConstrainedToSize:CGSizeMake(LabWidth, MAXFLOAT)];
        }
        else
        {
            size = [[item text] sizeConstrainedToSize:CGSizeMake(LabWidth, CellHeight)];
        }
        height = size.height;
    }
    if (height == 0 ) {
        height =  CellHeight;
    }
    return height;
}

+ (CGRect)rectWithImageSize:(CGSize)imageSize  Expend:(BOOL)expend
{
    CGRect  frame ;
    if (expend) {
        if (imageSize.width > ExpendImageWidth) {
            imageSize.height = ExpendImageWidth/imageSize.width *imageSize.height;
            imageSize.width = ExpendImageWidth;
        }
        frame = CGRectMake(ViewOffSetX, ViewOffSetY, imageSize.width, imageSize.height);
    }
    else
    {
        if (imageSize.width > CellHeight) {
            imageSize.height = CellHeight/imageSize.width *imageSize.height;
            imageSize.width = CellHeight;
        }
        frame = CGRectMake(ViewOffSetX, ViewOffSetY, imageSize.width, imageSize.height); //左对齐
    }
    return frame;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleGray;

        textLab = [[UILabel alloc]initWithFrame:CGRectMake(ViewOffSetX, ViewOffSetY, LabWidth, 0)];
        textLab.backgroundColor = UIClearColor;
        textLab.font= UIFontOfSize(15.0f);
        imageView = [[UIImageView alloc]initWithFrame:CGRectMake(ViewOffSetX, ViewOffSetY, 300, 0)];
        quotationImageView = [[UIImageView alloc] initWithFrame:CGRectMake(ViewOffSetX + 10 , ViewOffSetY + 4,5 ,0)];
        [quotationImageView setHidden:YES];
        [quotationImageView setBackgroundColor:UILightGrayColor];
        [self.contentView addSubview:quotationImageView];
    }
    return self;
}


-(void)setDraftItemInfo:(DraftItem *)item IsExpand:(BOOL)expend
{
    self.originItem = item;
    if (![item isPlain])
    {
        [imageView setHidden:NO];
        [textLab setHidden:NO];
        BOOL  isImage = [item isImage];
        if (isImage) {
            UIImage  *image = [item getImage];
            [textLab removeFromSuperview];
            [self.contentView addSubview:imageView];
            [imageView setImage:image];
            [imageView setFrame:[PreViewCell rectWithImageSize:image.size Expend:expend]];
        }else{
            if ([item isQuotation]) {
                [self configAsQuotation:expend item:item];
            }else{
                [self configAsText:expend item:item];
            }
          
        }
    }else{
        [imageView setHidden:YES];
        [textLab setHidden:YES];
    }
}

- (void)configAsText:(BOOL)expend item:(DraftItem *)item
{
    [quotationImageView setHidden:YES];
    CGSize size;
    if (expend) {
        size = [[item text] sizeConstrainedToSize:CGSizeMake(LabWidth, MAXFLOAT)];
        textLab.numberOfLines = 0;
    }
    else
    {
        size = [[item text] sizeConstrainedToSize:CGSizeMake(LabWidth, CellHeight)];
        textLab.numberOfLines = Lines;
    }
    [imageView removeFromSuperview];
    [self.contentView addSubview:textLab];
    [textLab setAttributedText:[item text]];
    [textLab setSize:size];
    
    [textLab setLeft:ViewOffSetX];
}
- (void)configAsQuotation:(BOOL)expend item:(DraftItem *)item
{
    [quotationImageView setHidden:NO];
    NSAttributedString  *text = [item text];
    if (item.isQuotation) {
        [textLab setText:[text string]];
        [textLab setFont:[UIFont italicSystemFontOfSize:16.0f]];
    }
    CGSize size;
    if (expend) {
        if (item.isQuotation) {
            size = [[text string] sizeWithFont:[UIFont italicSystemFontOfSize:16.0f] constrainedToSize:CGSizeMake(LabWidthQuotation, MAXFLOAT)];
        }else{
            size = [text sizeConstrainedToSize:CGSizeMake(LabWidthQuotation, MAXFLOAT)];
        }
        textLab.numberOfLines = 0;
    }
    else
    {
        if (item.isQuotation) {
            size = [[text string] sizeWithFont:[UIFont italicSystemFontOfSize:16.0f] constrainedToSize:CGSizeMake(LabWidthQuotation, CellHeight)];
        }else{
            size = [text sizeConstrainedToSize:CGSizeMake(LabWidthQuotation, CellHeight)];
        }
        textLab.numberOfLines = Lines;
    }
    [quotationImageView setHeight:size.height - 8];
    [imageView removeFromSuperview];
    [self.contentView addSubview:textLab];
    if (!item.isQuotation) {
        [textLab setAttributedText:text];
    }
    [textLab setSize:size];
    
    [textLab setLeft:ViewOffSetQuotationX];
}
-(void)prepareForMove
{
    [imageView setImage:nil];
    [textLab setText:nil];
    [[self textLabel] setText:@""];
	[[self detailTextLabel] setText:@""];
	[[self imageView] setImage:nil];
}

-(UIImageView*)checkmarkGreyImageView {
    if (!_checkmarkGreyImageView) {
        _checkmarkGreyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetHeight(self.frame), CGRectGetHeight(self.frame))];
        [_checkmarkGreyImageView setImage:[UIImage imageNamed:@"CheckmarkGrey"]];
        [_checkmarkGreyImageView setContentMode:UIViewContentModeCenter];
        [self.backView addSubview:_checkmarkGreyImageView];
    }
    return _checkmarkGreyImageView;
}

-(UIImageView*)checkmarkGreenImageView {
    if (!_checkmarkGreenImageView) {
        _checkmarkGreenImageView = [[UIImageView alloc] initWithFrame:self.checkmarkGreyImageView.bounds];
        [_checkmarkGreenImageView setImage:[UIImage imageNamed:@"CheckmarkGreen"]];
        [_checkmarkGreenImageView setContentMode:UIViewContentModeCenter];
        [self.checkmarkGreyImageView addSubview:_checkmarkGreenImageView];
    }
    return _checkmarkGreenImageView;
}


-(UIImageView*)deleteGreyImageView {
    if (!_deleteGreyImageView) {
        _deleteGreyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.contentView.frame), 0, CGRectGetHeight(self.frame), CGRectGetHeight(self.frame))];
        [_deleteGreyImageView setImage:[UIImage imageNamed:@"DeleteGrey"]];
        [_deleteGreyImageView setContentMode:UIViewContentModeCenter];
        [self.backView addSubview:_deleteGreyImageView];
    }
    return _deleteGreyImageView;
}

-(UIImageView*)deleteRedImageView {
    if (!_deleteRedImageView) {
        _deleteRedImageView = [[UIImageView alloc] initWithFrame:self.deleteGreyImageView.bounds];
        [_deleteRedImageView setImage:[UIImage imageNamed:@"DeleteRed"]];
        [_deleteRedImageView setContentMode:UIViewContentModeCenter];
        [self.deleteGreyImageView addSubview:_deleteRedImageView];
    }
    return _deleteRedImageView;
}

-(void)prepareForReuse {
	[super prepareForReuse];
	self.textLabel.textColor = [UIColor blackColor];
	self.detailTextLabel.text = nil;
	self.detailTextLabel.textColor = [UIColor grayColor];
	[self setUserInteractionEnabled:YES];
	self.imageView.alpha = 1;
	self.accessoryView = nil;
	self.accessoryType = UITableViewCellAccessoryNone;
    [self.contentView setHidden:NO];
    [_checkmarkProfileImageView removeFromSuperview];
    _checkmarkProfileImageView = nil;
    [self cleanupBackView];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
}

-(void)setFavourite:(BOOL)favourite animated:(BOOL)animated {
    self.isFavourite = favourite;
    if (animated) {
        if (favourite) {
            CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"borderColor"];
            animation.toValue = (id)[UIColor colorWithRed:0.149 green:0.784 blue:0.424 alpha:0.750].CGColor;
            animation.fromValue = (id)[UIColor colorWithWhite:0 alpha:0.3].CGColor;
            animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
            animation.duration = 0.25;
            [self.checkmarkProfileImageView setAlpha:0];
            [UIView animateWithDuration:0.25
                             animations:^{
                                 [self.checkmarkProfileImageView setAlpha:1];
                             }];
        } else {
            CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"borderColor"];
            animation.toValue = (id)[UIColor colorWithWhite:0 alpha:0.3].CGColor;
            animation.fromValue = (id)[UIColor colorWithRed:0.149 green:0.784 blue:0.424 alpha:0.750].CGColor;
            animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
            animation.duration = 0.25;
            [UIView animateWithDuration:0.25
                             animations:^{
                                 [self.checkmarkProfileImageView setAlpha:0];
                             }
                             completion:^(BOOL finished) {
                                 [_checkmarkProfileImageView removeFromSuperview];
                             }];
        }
    } else {
        if (favourite) {
            [self.checkmarkProfileImageView setAlpha:1];
        } else {
            [self.checkmarkProfileImageView setAlpha:0];
            [_checkmarkProfileImageView removeFromSuperview];
        }
    }
}

-(void)animateContentViewForPoint:(CGPoint)point velocity:(CGPoint)velocity {
    [super animateContentViewForPoint:point velocity:velocity];
    if (point.x > 0) {
        // set the checkmark's frame to match the contentView
        [self.checkmarkGreyImageView setFrame:CGRectMake(MIN(CGRectGetMinX(self.contentView.frame) - CGRectGetWidth(self.checkmarkGreyImageView.frame), 0), CGRectGetMinY(self.checkmarkGreyImageView.frame), CGRectGetWidth(self.checkmarkGreyImageView.frame), CGRectGetHeight(self.checkmarkGreyImageView.frame))];
        if (point.x >= EffectiveDistance(self.frame) && self.isFavourite == NO) {
            [self.checkmarkGreenImageView setAlpha:1];
        } else if (self.isFavourite == NO) {
            [self.checkmarkGreenImageView setAlpha:0];
        } else if (point.x >= EffectiveDistance(self.frame) && self.isFavourite == YES) {
            // already a favourite; animate the green checkmark drop when swiped far enough for the action to kick in when user lets go
            if (self.checkmarkGreyImageView.alpha == 1) {
                [UIView animateWithDuration:0.25
                                 animations:^{
                                     CATransform3D rotate = CATransform3DMakeRotation(-0.4, 0, 0, 1);
                                     [self.checkmarkGreenImageView.layer setTransform:CATransform3DTranslate(rotate, -10, 20, 0)];
                                     [self.checkmarkGreenImageView setAlpha:0];
                                 }];
            }
        } else if (self.isFavourite == YES) {
            // already a favourite; but user panned back to a lower value than the action point
            CATransform3D rotate = CATransform3DMakeRotation(0, 0, 0, 1);
            [self.checkmarkGreenImageView.layer setTransform:CATransform3DTranslate(rotate, 0, 0, 0)];
            [self.checkmarkGreenImageView setAlpha:1];
        }
    } else if (point.x < 0) {
        // set the X's frame to match the contentView
        [self.deleteGreyImageView setFrame:CGRectMake(MAX(CGRectGetMaxX(self.frame) - CGRectGetWidth(self.deleteGreyImageView.frame), CGRectGetMaxX(self.contentView.frame)), CGRectGetMinY(self.deleteGreyImageView.frame), CGRectGetWidth(self.deleteGreyImageView.frame), CGRectGetHeight(self.deleteGreyImageView.frame))];
        if (-point.x >= EffectiveDistance(self.frame)) {
            [self.deleteRedImageView setAlpha:1];
        } else {
            [self.deleteRedImageView setAlpha:0];
        }
    }
}

-(void)resetCellFromPoint:(CGPoint)point velocity:(CGPoint)velocity {
    [super resetCellFromPoint:point velocity:velocity];
    if (point.x > 0 && point.x <= EffectiveDistance(self.frame)) {
        // user did not swipe far enough, animate the checkmark back with the contentView animation
        [UIView animateWithDuration:self.animationDuration
                         animations:^{
                             [self.checkmarkGreyImageView setFrame:CGRectMake(-CGRectGetWidth(self.checkmarkGreyImageView.frame), CGRectGetMinY(self.checkmarkGreyImageView.frame), CGRectGetWidth(self.checkmarkGreyImageView.frame), CGRectGetHeight(self.checkmarkGreyImageView.frame))];
                         }];
    } else if (point.x < 0) {
        if (-point.x <= EffectiveDistance(self.frame)) {
            // user did not swipe far enough, animate the grey X back with the contentView animation
            [UIView animateWithDuration:self.animationDuration
                             animations:^{
                                 [self.deleteGreyImageView setFrame:CGRectMake(CGRectGetMaxX(self.frame), CGRectGetMinY(self.deleteGreyImageView.frame), CGRectGetWidth(self.deleteGreyImageView.frame), CGRectGetHeight(self.deleteGreyImageView.frame))];
                             }];
        } else {
            // user did swipe far enough to meet the delete action requirement, animate the Xs to show selection
            [UIView animateWithDuration:self.animationDuration
                             animations:^{
                                 [self.deleteGreyImageView.layer setTransform:CATransform3DMakeScale(1, 1, 1)];
                                 [self.deleteGreyImageView setAlpha:0];
                                 [self.deleteRedImageView.layer setTransform:CATransform3DMakeScale(1, 1, 1)];
                                 [self.deleteRedImageView setAlpha:0];
                             }];
        }
    }
}

-(void)cleanupBackView {
    [super cleanupBackView];
    [_checkmarkGreyImageView removeFromSuperview];
    _checkmarkGreyImageView = nil;
    [_checkmarkGreenImageView removeFromSuperview];
    _checkmarkGreenImageView = nil;
    [_deleteGreyImageView removeFromSuperview];
    _deleteGreyImageView = nil;
    [_deleteRedImageView removeFromSuperview];
    _deleteRedImageView = nil;
}

- (void)drawRect:(CGRect)rect
{
    
}

-(void)dealloc
{
    UIRelease(textLab);
    UIRelease(imageView);
    UIRelease(quotationImageView);
    UIRelease(originItem);
    [super dealloc];
}


@end
